const express = require("express");
const app = express();
app.set("view engine", "ejs");

//01应用级中间件
app.use((req, res, next) => { /*匹配任何路由*/
    console.log(new Date());
    next(); /*执行完中间件后继续向下执行*/
});

app.get("/", (req, res) => {
    res.send("这是express中间件");
});

//02路由中间件
app.get("/news", (req, res, next) => {
    console.log("这是news路由中间件");
    next();
});

app.get("/news", (req, res) => {
    res.send("这是news模块");
});

//03内置中间件
app.use('/public', express.static("./static"));

//04第三方中间件 body-parser获取post提交的数据的中间件
const bodyParser = require("body-parser");
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended: false}));
// parse application/json
app.use(bodyParser.json());

app.get("/login", (req, res) => {
    res.render("login", {});
});

app.post("/dologin", (req, res) => {
    res.send(req.body);
});

//05错误处理中间件，注意要放在代码最后
app.use(function (req, res) {
    res.status(404).render('404', {msg: "404，没有匹配的路由"});
});

app.listen(8080);